package com.ysten.basic.web.system;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.ysten.basic.common.utils.SystemConfigLoader;

@Slf4j
@Controller
@RequestMapping(value = "/upload")
public class UploadController
{
    
    final static String UPLOAD_DIR = "static/images/upload";
    
    private final String FILE_SER = "/";
    
    private UploadManager uploadManager = new UploadManager();
    
    @Autowired
    private SystemConfigLoader systemConfigLoader;
    
    /**
     * 上传文件
     * 
     * @return
     * @throws InterruptedException
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "/uploadify", method = RequestMethod.POST)
    @ResponseBody
    public String upload(HttpServletRequest request, HttpServletResponse response)
        throws IOException, InterruptedException
    {
        String accessKey = systemConfigLoader.getStringValue("qiniu.accessKey");
        String secretKey = systemConfigLoader.getStringValue("qiniu.secretKey");
        String storageName = systemConfigLoader.getStringValue("qiniu.storage.name");
        String qiniuUrl = systemConfigLoader.getStringValue("qiniu.http.url");
        Auth auth = Auth.create(accessKey, secretKey);
        log.debug("upload() start");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String ctxPath = request.getSession().getServletContext().getRealPath("/") + FILE_SER + UPLOAD_DIR;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String ymd = sdf.format(new Date());
        ctxPath += FILE_SER + ymd + FILE_SER;
        log.debug("upload() ctxPath = " + ctxPath);
        
        // 创建文件夹
        File file = new File(ctxPath);
        if (!file.exists())
        {
            if (file.mkdirs())
            {
                log.debug("upload() 创建文件夹成功 ");
            }
            else
            {
                log.debug("upload() 创建文件夹失败 ");
                
            }
        }
        
        String fileName = null;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet())
        {
            // 上传文件
            MultipartFile mf = entity.getValue();
            fileName = mf.getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
            File uploadFile = new File(ctxPath + newFileName);
            try
            {
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                Response rs = uploadManager.put(uploadFile, newFileName, auth.uploadToken(storageName));
                uploadFile.delete();
                if (rs.isOK())
                {
                    fileName = qiniuUrl + newFileName;
                }
                else
                {
                    fileName = "上传失败!";
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            
        }
        
        log.debug("upload() end");
        
        return fileName;
    }
}
